import tkinter as tk
from tkinter import messagebox, ttk
from tkinter import filedialog
from pdf2docx import Converter
import tabula
import pandas as pd
import subprocess
import os

class FileConversionUI:
    def __init__(self):
        self.root = tk.Tk()
        self.setup_ui()

    def setup_ui(self):
        self.root.title("文件格式转换")
        self.root.geometry("400x300")

        main_frame = ttk.Frame(self.root, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 返回按钮
        back_btn = ttk.Button(main_frame, text="返回主界面", command=self.back_to_main)
        back_btn.pack(anchor='w', pady=10)

        # 功能按钮区域
        btn_frame = ttk.Frame(main_frame)
        btn_frame.pack(pady=20)

        # 定义按钮样式
        style = ttk.Style()
        style.configure('Custom.TButton',
                        font=('Arial', 12),  # 设置字体和大小
                        background='#4CAF50',  # 设置背景颜色
                        foreground='black',  # 设置文字颜色
                        borderwidth=2,  # 设置边框宽度
                        relief='raised')  # 设置边框样式
        # 定义鼠标悬停样式
        style.map('Custom.TButton',
                  background=[('active', '#45a049')])  # 鼠标悬停时的背景颜色

        # PDF 转 Word 按钮
        pdf_to_word_btn = ttk.Button(btn_frame, text="PDF 转 Word", command=self.pdf_to_word, style='Custom.TButton')
        pdf_to_word_btn.pack(fill=tk.X, pady=5)

        # PDF 转 Excel 按钮
        pdf_to_excel_btn = ttk.Button(btn_frame, text="PDF 转 Excel", command=self.pdf_to_excel, style='Custom.TButton')
        pdf_to_excel_btn.pack(fill=tk.X, pady=5)

    def back_to_main(self):
        """返回主界面"""
        self.root.destroy()
        from gui_main import Application
        Application().run()

    def pdf_to_word(self):
        """PDF 转 Word 功能实现"""
        try:
            # 打开文件选择对话框
            pdf_path = filedialog.askopenfilename(filetypes=[("PDF Files", "*.pdf")])
            if not pdf_path:
                return
            # 选择保存路径
            word_path = filedialog.asksaveasfilename(defaultextension=".docx", filetypes=[("Word Files", "*.docx")])
            if not word_path:
                return
            # 执行转换
            cv = Converter(pdf_path)
            cv.convert(word_path)
            cv.close()
            messagebox.showinfo("提示", "PDF 转 Word 成功！")
        except Exception as e:
            messagebox.showerror("错误", f"PDF 转 Word 失败：{str(e)}")

    def pdf_to_excel(self):
        """PDF 转 Excel 功能实现"""
        try:
            java_home = "C:\\Program Files\\Java\\jdk1.8.0_191"  # Windows 示例
            java_path = os.path.join(java_home, "bin", "java.exe")  # Windows 示例
            try:
                result = subprocess.run([java_path, "-version"], capture_output=True, text=True)
                print("Java version output:", result.stderr)  # java -version 输出到 stderr
            except Exception as e:
                print("Failed to run Java:", e)

            os.environ["JAVA_HOME"] = java_home
            os.environ["PATH"] = f"{java_home}\\bin;{os.environ['PATH']}"

            # 打开文件选择对话框
            pdf_path = filedialog.askopenfilename(filetypes=[("PDF Files", "*.pdf")])
            if not pdf_path:
                return
            # 选择保存路径
            excel_path = filedialog.asksaveasfilename(defaultextension=".xlsx", filetypes=[("Excel Files", "*.xlsx")])
            if not excel_path:
                return
            # 读取 PDF 表格数据
            dfs = tabula.read_pdf(pdf_path, pages='all')
            # 将数据写入 Excel 文件
            with pd.ExcelWriter(excel_path) as writer:
                for i, df in enumerate(dfs):
                    df.to_excel(writer, sheet_name=f'Sheet{i + 1}', index=False)
            messagebox.showinfo("提示", "PDF 转 Excel 成功！")
        except Exception as e:
            messagebox.showerror("错误", f"PDF 转 Excel 失败：{str(e)}")

    def run(self):
        self.root.mainloop()
